from flask import Flask, render_template, request, url_for, redirect, make_response
from flask_sqlalchemy import SQLAlchemy
import datetime
import time
import json

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/py02db?charset=utf8'

db = SQLAlchemy(app)
class User(db.Model):
    id = db.Column('id', db.Integer, primary_key=True)
    u_id = db.Column(db.String(10), unique=True)
    u_name = db.Column(db.String(128), unique=True)
    u_pass = db.Column(db.String(16))

    def __init__(self, uid, uname, upass):
        self.u_id = uid
        self.u_name = uname
        self.u_pass = upass


class clist(db.Model):
    id = db.Column('id', db.Integer, primary_key=True)
    c_id = db.Column(db.String(10))
    c_name = db.Column(db.String(128))
    u_id = db.Column(db.String(10))

    def __init__(self, cid, cname, uid):
        self.c_id = cid
        self.c_name = cname
        self.u_id = uid

class stu(db.Model):
    id = db.Column('id', db.Integer, primary_key=True)
    s_id = db.Column(db.String(10))
    s_name = db.Column(db.String(128))
    s_age = db.Column(db.Integer)
    s_sex = db.Column(db.String(1))
    c_name = db.Column(db.String(128))
    c_id = db.Column(db.String(10))

    def __init__(self, sid,sname,age,sex,cname,cid):
        self.s_id = sid
        self.s_name = sname
        self.s_age = age
        self.s_sex = sex
        self.c_name = cname
        self.c_id = cid


@app.route('/index.html')
@app.route('/')
def home_page():
    cookie = request.cookies
    if cookie:
        un = cookie.get('UN')
        up = cookie.get('UP')
        # class default value
        cdv = cookie.get('CDV')
        res = User.query.filter_by(u_name=un).first()
        if res:
            if res.u_pass == up:
                cdatas = clist.query.filter_by(u_id=res.u_id).all()
                if cdatas:
                    new_cdv = ''
                    if cdv:
                        new_cdv = cdv
                    else:
                        new_cdv = cdatas[0].c_id

                    index = 0
                    for idx, item in enumerate(cdatas):
                        if new_cdv == item.c_id:
                            index = idx

                    all_stu = stu.query.filter_by(c_id=new_cdv).all()


                    return render_template('index.html', userInfo={'un': un, 'up': up}, c_data=cdatas, students=all_stu, index=index+1)
                else:
                    return u'没有班级，先创建班级'
            else:
                return u'密码错误，请联系管理员'
        else:
            return u'用户不存在'

    else:
        return render_template('login.html')

    return u'主页'


# TODO:注册


# TODO:登录页面
@app.route('/user/login/')
def user_login():
    return render_template('login.html')

# TODO:用户登录验证
@app.route('/login', methods=['POST'])
def access_login():
    un = request.form['uname']
    up = request.form['upass']

    # 1'正则验证 有没有 怪异字符
    # 2'数据库验证
    res = User.query.filter_by(u_name=un).first()
    if res:
        if res.u_pass == up:
            # 用户名密码匹配
            resp = make_response(render_template('login.html', userinfo={'un': un}))
            resp.set_cookie('UN', un)
            resp.set_cookie('UP', up)
            return resp
        else:
            return u'密码错误，请联系管理员'
    else:
        return u'用户不存在，请联系管理员'

# TODO:查询班级学生
@app.route('/students')
def all_students():
    resp = make_response(redirect(url_for('home_page')))
    resp.set_cookie('CDV',request.args.get('classname'))
    return resp
    #return u'正在查询...'

# TODO:增加班级学生
@app.route('/add2', methods=['POST'])
def add_student2():
    sname = request.form['sname']
    sclass = request.form['sclass']

    #1.查询数据库
    #2.添加到数据库
    #3.将该班所有的学生重新进行刷新
    students = [
        {'sn':'pony ma','sage':18},
        {'sn': 'pony ma2', 'sage': 20},
        {'sn': 'pony ma3', 'sage': 21},
        {'sn': 'pony ma4', 'sage': 19}
    ]

    return render_template('index.html', students=students)

@app.route('/add', methods=['POST'])
def add_student():
    sn = request.form['sname']
    sid = time.time()
    print(str(int(sid)))
    sid = str(int(sid))
    sex = request.form['ssex']
    age = int(request.form['sage'])
    cname = request.form['cname']
    classes = clist.query.filter_by(c_name=cname).first()

    if classes:
        cid = classes.c_id
    else:
        cid = '000000'

    # 添加 学员
    db.session.add(stu(sid, sn, age, sex, cname, cid))
    db.session.commit()

    return redirect(url_for('home_page'))
    # return redirect('/')


# TODO:删除学员
@app.route('/deleteone')
def delete_one():
    return render_template('delete.html')

# TODO:更新学员信息
@app.route('/updateone', methods=['POST'])
def update_one():

    return redirect('/')


# TODO:Ajax HTML
@app.route('/ajax')
def ajax():
    return render_template('ajax.html')

# TODO:获取学生信息
@app.route('/allusers')
def all_users():
    data = {
        'message': '成功'
    }
    return json.dumps(data,ensure_ascii=False)

@app.route('/ds')
def ds():
    data = {
        'datas': [
            {'sname':'Pony Ma','age': 18},
            {'sname': 'Pony Ma2', 'age': 108},
            {'sname': 'Pony Ma3', 'age': 180},
            {'sname': 'Pony Ma5', 'age': 1},
            {'sname': 'Pony Ma6', 'age': 8},
            {'sname': 'Pony Ma7', 'age': 81}
        ],
        'user':{
            'un': request.args.get('un')
        }
    }

    return json.dumps(data,ensure_ascii=False)


if __name__ == '__main__':
    app.run()
